package klk.shop.servlets.contentServlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import klk.shop.objects.Article;
import klk.shop.objects.Category;

/**
 * Servlet implementation class ArticleAdministrationContentServlet
 */
@WebServlet("/ArticleAdministrationContentServlet")
public class ArticleAdministrationContentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Article article;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ArticleAdministrationContentServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String path = request.getContextPath() + "/";

		HttpSession session = request.getSession();
		Properties languageLocale = (Properties) session
				.getAttribute("languageProperty");
		String languageString = languageLocale.getProperty("locale", "en");

		article = new Article();

		// === POST-Parameter-Behandlung
		Map<String, String[]> map = request.getParameterMap();
		int[] categoryIds=null;
		//String[] tags;
		boolean isConsistent = true;
		if (map.containsKey("add")) {
			if (map.containsKey("name_de") && (map.get("name_de")).length > 0) {
				article.setName((map.get("name_de"))[0]);
			} else
				isConsistent = false;
			if (map.containsKey("article_details_de")
					&& (map.get("article_details_de")).length > 0) {
				article.setDescription((map.get("article_details_de"))[0]);
			} else
				isConsistent = false;

			if (map.containsKey("price") && (map.get("price")).length > 0) {
				try {
					article.setNetPrice(Double.parseDouble((map.get("price"))[0]));
				} catch (NumberFormatException nfe) {
					isConsistent = false;
				}
			} else
				isConsistent = false;
			if (map.containsKey("stock") && (map.get("stock")).length > 0) {
				try {
					article.setStockAmount(Integer.parseInt((map.get("stock"))[0]));
				} catch (NumberFormatException nfe) {
				}
			}
			if (map.containsKey("tax") && (map.get("tax")).length > 0) {
				try {
					article.setTax(Double.parseDouble((map.get("tax"))[0]));
				} catch (NumberFormatException nfe) {
				}
			}
			if (map.containsKey("height") && (map.get("height")).length > 0) {
				try {
					article.setHeight(Double.parseDouble((map.get("height"))[0]));
				} catch (NumberFormatException nfe) {
				}
			}
			if (map.containsKey("width") && (map.get("width")).length > 0) {
				try {
					article.setWidth(Double.parseDouble((map.get("width"))[0]));
				} catch (NumberFormatException nfe) {
				}
			}
			if (map.containsKey("depth") && (map.get("depth")).length > 0) {
				try {
					article.setDepth(Double.parseDouble((map.get("depth"))[0]));
				} catch (NumberFormatException nfe) {
				}
			}
			if (map.containsKey("weight") && (map.get("weight")).length > 0) {
				try {
					article.setWeight(Double.parseDouble((map.get("weight"))[0]));
				} catch (NumberFormatException nfe) {
				}
			}
			if (map.containsKey("new")) {
				article.setNewArticle(true);
			}
			if (map.containsKey("promo")) {
				article.setOffer(true);
			}
			if (map.containsKey("bulky")) {
				article.setBulky(true);
			}
			if (map.containsKey("discontinued")) {
				article.setDiscontinued(true);
			}
			if (map.containsKey("tags") && (map.get("tags")).length > 0) {
				/*
				 * tags = (map.get("tags"))[0].split(","); for (int i = 0; i <
				 * tags.length; i++) article.addTag(tags[i]);
				 */
			}
			if (map.containsKey("categories")
					&& (map.get("categories")).length > 0) {
				String categoryNames[] = map.get("categories");
				categoryIds = new int[categoryNames.length];
				for (int i = 0; i < categoryNames.length; i++) {
					categoryIds[i]=Integer.parseInt(categoryNames[i]);
					article.addCategory(categoryIds[i], languageString);
				}
			} else
				isConsistent = false;
		} else
			isConsistent = false;

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<div class='left_content'>");
		out.println("<div class='title'><span class='title_icon'><img src='images/bullet1.gif' alt='' title='' /></span>Add new article</div>");
		if (!isConsistent) {
			out.println("<div class='feat_prod_box_details'>");
			out.println("<p class='details'>");
			out.println("Descritption area.");
			out.println("</p>");
			out.println("<div class='contact_form'>");
			out.println("<div class='form_subtitle'>* requierd fields</div>");
			out.println("<div class='form_row'>");
			out.println("<form method='POST' name='add_article'>");
			out.println("<label class='contact'><strong>Name (de)*:</strong></label>");
			out.println("<input type='text' class='contact_input' name='name_de' />");
			out.println(map.containsKey("add") ? parameterStringError(request
					.getParameter("name_de")) : "");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Name (en):</strong></label>");
			out.println("<input type='text' class='contact_input' name='name_en' />");
			out.println();
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Name(fr):</strong></label>");
			out.println("<input type='text' class='contact_input' name='name_fr' />");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Details(de)*:</strong></label>");
			out.println("<textarea class='contact_textarea' name='article_details_de' ></textarea>");
			out.println(map.containsKey("add") ? parameterStringError(request
					.getParameter("article_details_de")) : "");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Details (en):</strong></label>");
			out.println("<textarea class='contact_textarea' name='article_details_en' ></textarea>");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Details (fr):</strong></label>");
			out.println("<textarea class='contact_textarea' name='article_details_fr' ></textarea>");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Net price*:</strong></label>");
			out.println("<input type='text' class='contact_input' name='price' />");
			out.println(map.containsKey("add") ? parameterStringError(request
					.getParameter("price")) : "");
			out.println(map.containsKey("add") ? parameterDoubleError(request
					.getParameter("price")) : "");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Stock:</strong></label>");
			out.println("<input type='text' class='contact_input' name='stock' />");
			out.println(map.containsKey("add") ? parameterDoubleError(request
					.getParameter("stock")) : "");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Tax:</strong></label>");
			out.println("<input type='text' class='contact_input' name='tax' />");
			out.println(map.containsKey("add") ? parameterDoubleError(request
					.getParameter("tax")) : "");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Height (cm):</strong></label>");
			out.println("<input type='text' class='contact_input' name='height' />");
			out.println(map.containsKey("add") ? parameterDoubleError(request
					.getParameter("height")) : "");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Width (cm):</strong></label>");
			out.println("<input type='text' class='contact_input' name='width' />");
			out.println(map.containsKey("add") ? parameterDoubleError(request
					.getParameter("width")) : "");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Depth (cm):</strong></label>");
			out.println("<input type='text' class='contact_input' name='depth' />");
			out.println(map.containsKey("add") ? parameterDoubleError(request
					.getParameter("depth")) : "");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Weight (kg):</strong></label>");
			out.println("<input type='text' class='contact_input' name='weight' />");
			out.println(map.containsKey("add") ? parameterDoubleError(request
					.getParameter("weight")) : "");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Attributes:</strong></label>");
			out.println("<div class='terms'>");
			out.println("<input type='checkbox' name='new' />");
			out.println("New article");
			out.println("</div>");
			out.println("<div class='terms'>");
			out.println("<input type='checkbox' name='promo' />");
			out.println("Promotion");
			out.println("</div>");
			out.println("<div class='terms'>");
			out.println("<input type='checkbox' name='discontinued' />");
			out.println("Discontinued");
			out.println("</div>");
			out.println("<div class='terms'>");
			out.println("<input type='checkbox' name='bulky' />");
			out.println("Bulky");
			out.println("</div>");
			out.println("</div>");
			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Tags:</strong></label>");
			out.println("<input type='text' class='contact_input' name='tags' disabled />");
			out.println("<div class='terms'>You can use commas to seperate multiple tags.</div>");
			out.println("</div>");

			out.println("<div class='form_row'>");
			out.println("<label class='contact'><strong>Kategories*:</strong></label>");
			out.println("<p>");

			Hashtable<Integer, String> table = Category
					.getCategoryNames(languageString);
			ArrayList<Integer> list = Category
					.getSortedCategoryIds(languageString);

			out.println("<select name='categories' size='" + table.size()
					+ "' multiple class='contact_select'>");

			for (int i = 0; i < list.size(); i++) {
				out.print("<option value='");

				out.print(list.get(i));
				out.print(i == 0 ? "' selected >" : "'>");
				out.print(table.get(list.get(i)));
				out.println("</option>");
			}
			out.println("    </select>");
			out.println("  </p>");
			out.println("</div>");

			out.println("<div class='form_row'>");
			out.println("<input type='submit' name='add' class='register' value='save' /></form>");
			out.println("</div>");
			out.println("</div>");
			out.println("</div>");
		} else {
			out.println("<div class='feat_prod_box_details'>");
			out.println("<p class='details'>");
			if (article.addToSql(categoryIds,
					request.getParameterValues("tags")))
				out.println("Artikel added to catalog.");
			else
				out.println("FAILED adding to catalog.");
			out.println("</p>");
			out.println(article.toHtml(path));
			System.out.println(article.toString());
			out.println("</div>");
		}

		out.println("<div class='clear'></div>\n");
		out.println("</div><!--end of left content-->");
	}

	private StringBuilder parameterStringError(String parameterValue) {
		StringBuilder sb = new StringBuilder("");
		if (parameterValue == null || parameterValue.isEmpty()) {
			sb.append("<div class='terms'>\n");
			sb.append("\t<b>required</b>\n");
			sb.append("</div>\n");
			return sb;
		} else
			return sb;
	}

	private StringBuilder parameterDoubleError(String value) {
		StringBuilder sb = new StringBuilder("");
		if (value.isEmpty() || value == null)
			return sb;
		try {
			Double.parseDouble(value);
			return sb;
		} catch (NumberFormatException nfe) {
			sb.append("<div class='terms'>\n");
			sb.append("\t<b>wrong format</b>\n");
			sb.append("</div>\n");
			return sb;
		}
	}

}
